#include <cstdio>
#include <iostream>
#include "HEpoll.h"
#include "AliasRef.h"

#define CHKRET(r) if(r){printf(#r "=%d\n", r); return r;}

int main(int, char**)
{
    HEpoll hep;
    int ret = hep.init();
    CHKRET(ret);
    hep.run(true);

    hep.setAliasNameInstance(make_shared<AliasRef<ConnectMetaSPtr>>());

    int timerfd = hep.addTimer(2, true, [=](int fd){
        printf("main cb fd=%d\n", fd);
    });

    auto lisnMeta = hep.addTcpListen(8888);
    lisnMeta->start();

    ConnectMetaSPtr connMeta;
    string input;
    while (cin >> input, input != "q")
    {
        // cout << input << " |size=" << input.size() << endl;
        if ("d" == input)
        {
            hep.delTimer(timerfd);
            cout << "timer removed " << timerfd << endl;
        }
        else if ("s" == input)
        {
            if (connMeta)
            {
                if (connMeta->sendMsg("dd"))
                {
                    cout << "send fail, connMeta is " << connMeta->toString() << endl;
                    connMeta->stop(false);
                    connMeta.reset();
                }
            }
        }
        else if ("f" == input)
        {
            const string findStrArr[] = {"abc", "as-163", "as-162"};
            for (auto str : findStrArr)
            {
                auto ptr = hep.find(str);
                cout << "find " << str << " result is " << ptr << endl;
            }
        }
        else if ("c" == input)
        {
            connMeta = hep.addTcpConnect2("www.163.com", 80, 3, 
                [](bool result, ConnectMetaSPtr cmp){
                printf("connect %s\n", result? "success": "fail");
            });
            connMeta->setName("163Sendder");
            hep.addAliasName("as-163", connMeta);
            //connMeta->sendMsg("hello\n");
            connMeta->start();
            cout << "connMeta is " << connMeta->toString() << endl;
        }

        input.clear();
    }

    printf("notify Exit");
    hep.notifyExit();
    hep.unInit();
    return 0;
}